package net.hn.hnms.biz.gasext.dws.service.impl;

import com.alibaba.excel.util.DateUtils;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.SneakyThrows;
import net.hn.hnms.biz.api.mine.RemoteMineInfoService;
import net.hn.hnms.biz.api.safety.gasext.domain.*;
import net.hn.hnms.biz.api.safety.gasext.domain.dto.LeadInfoDto;
import net.hn.hnms.biz.api.safety.location.model.LeadVo;
import net.hn.hnms.biz.api.safety.location.model.OutLimitAlarmingInfoVO;
import net.hn.hnms.biz.gasext.dws.domain.dto.EffectiveProductionTimeByMineCodeDto;
import net.hn.hnms.biz.gasext.dws.domain.vo.*;
import net.hn.hnms.biz.gasext.dws.mapper.*;
import net.hn.hnms.biz.gasext.dws.service.AqjkService;
import net.hn.hnms.biz.gasext.dws.service.DwdRydwService;
import net.hn.hnms.biz.gasext.dws.service.DwdService;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.core.utils.StringUtils;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import net.hn.hnms.sys.common.redis.domain.SysOrganization;
import net.hn.hnms.sys.common.redis.utils.RedisUtils;
import net.hn.hnms.sys.system.api.domain.SysDictData;
import net.hn.hnms.biz.gasext.dws.domain.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service
@DS(value = "dwd")
public class DwdServiceImpl implements DwdService {

    @Resource
    private DwdAqjcCdssHMapper dwdAqjcCdssHMapper;

    @Resource
    private DwdAqjcCdssDMapper dwdAqjcCdssDMapper;
    @Resource
    private DwdAqjcYcbjDMapper dwdAqjcYcbjDMapper;

    @Resource
    private DwdRydwRyjzDMapper dwdRydwRyjzDMapper;

    @Resource
    private DwdRydwRyssHMapper dwdRydwRyssHMapper;
    @Resource
    private DwdRydwRyssDMapper dwdRydwRyssDMapper;

    @Resource
    private DwdRydwRyxxDMapper dwdRydwRyxxDMapper;

    @Resource
    private RemoteMineInfoService remoteMineInfoService;

    @Resource
    private DwdAqjcCddyDMapper dwdAqjcCddyDMapper;
    @Resource
    private JyglDwmcEntityMapper jyglDwmcEntityMapper;

    @Resource
    private JyglInsertShiftManage1Mapper jyglInsertShiftManage1Mapper;

    @Resource
    private JyglShiftManagementMapper jyglShiftManagementMapper;
    @Resource
    private AqjkService aqjkService;

    @Resource
    private DimCoalMineBasicInfoMapper dimCoalMineBasicInfoMapper;
    @Resource
    private CoalMineBasicDisasterIntelligentInfoMapper coalMineBasicDisasterIntelligentInfoMapper;

    @Resource
    private DwdLtkClrydwSssjHMapper dwdLtkClrydwSssjHMapper;

    @Resource
    private DwdRydwService dwdRydwService;

    @Resource
    private DwdCoalMineProduceDurationRtDMapper dwdCoalMineProduceDurationRtDMapper;

    @Resource
    private DmZdsbZtfTfssYxztRtHMapper dmZdsbZtfTfssYxztRtHMapper;
    @Resource
    private DwdZdsbZcxtZcssTmpRtHMapper dwdZdsbZcxtZcssTmpRtHMapper;
    @Resource
    private DmZdsbZjtsztRtHMapper dmZdsbZjtsztRtHMapper;
    /**
     * 大屏首页-安全检测（本地数据）
     * @return
     */
    @SneakyThrows
    @Override
    public SafetyMonitoringVo getSafetyMonitoringLocl(String companyCode, String mineCode) {


        SafetyMonitoringVo safetyMonitoringVo = new SafetyMonitoringVo();
        //煤矿列表集合
        List<MinePointInAlarmfoVo> minePointInAlarmfoVoList = new ArrayList<>();
        //获取所有煤矿
        List<DimCoalMineBasicInfoPo> list = aqjkService.selectCodeUndergSubMineInfoList(companyCode, mineCode);

        //去除露天矿
        //魏家峁 150622B0012000210118
        // 铧尖  未知
        // 伊敏  150724B0012000510053
        //20240809 去除 刘园子：621022009406  和  马蹄沟：620824009852
//        List<String> codesToRemove = Arrays.asList("150622B0012000210118", "150724B0012000510053","621022009406","620824009852");
//        list = list.stream()
//                .filter(dto -> !codesToRemove.contains(dto.getOrgCode()))
//                .collect(Collectors.toList());


        final Integer[] ch4Number = {0};
        final Integer[] coNumber = {0};
        // 初始化计数器，初始计数为
        CountDownLatch countDownLatch = new CountDownLatch(list.size());
        for (int i = 0, listSize = list.size(); i < listSize; i++) {
            DimCoalMineBasicInfoPo dimCoalMineBasicInfoPo = list.get(i);
            new Thread(() -> {
                try {
                    //查询当前煤矿的所有测点 实时表
                    Integer pointNumber = dwdAqjcCdssHMapper.selectPointNumber(dimCoalMineBasicInfoPo.getMkCode());
                    //一氧化碳报警
                    Integer coWarnCount = dwdAqjcCdssHMapper.selectCoWarnCount(dimCoalMineBasicInfoPo.getMkCode());
                    //甲烷报警
                    Integer ch4WarnCount = dwdAqjcCdssHMapper.selectCH4WarnCount(dimCoalMineBasicInfoPo.getMkCode());
                    MinePointInAlarmfoVo minePointInAlarmfoVo = new MinePointInAlarmfoVo();
                    minePointInAlarmfoVo.setMineCode(dimCoalMineBasicInfoPo.getMkCode());
                    minePointInAlarmfoVo.setMineName(dimCoalMineBasicInfoPo.getMkFullName());
                    minePointInAlarmfoVo.setPointNumber(pointNumber);
                    minePointInAlarmfoVo.setCoWarnCount(coWarnCount);
                    minePointInAlarmfoVo.setCH4WarnCount(ch4WarnCount);
                    //煤矿顺序
                    minePointInAlarmfoVo.setMkRank(dimCoalMineBasicInfoPo.getMkRank() != null ? dimCoalMineBasicInfoPo.getMkRank() : 99);
                    minePointInAlarmfoVoList.add(minePointInAlarmfoVo);


                    //甲烷测点数
                    Integer ch4NumberInteger = dwdAqjcCdssHMapper.selectCH4NumberAll(dimCoalMineBasicInfoPo.getMkCode());
                    ch4Number[0] = ch4Number[0] + ch4NumberInteger;
                    //一氧化碳测点数
                    Integer coNumberInteger = dwdAqjcCdssHMapper.selectCONumberAll(dimCoalMineBasicInfoPo.getMkCode());
                    coNumber[0] = coNumber[0] + coNumberInteger;
                    // 调用countDown()计算减1
                    countDownLatch.countDown();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }, String.valueOf(i)).start();

        }
        // 调用计算器的await方法
        countDownLatch.await();


        //计算测点总数
        int pointNumberSum = minePointInAlarmfoVoList.stream()
                .mapToInt(MinePointInAlarmfoVo::getPointNumber)
                .sum();

        //计算CH4超限数
        int cH4WarnCountSum = minePointInAlarmfoVoList.stream()
                .mapToInt(MinePointInAlarmfoVo::getCH4WarnCount)
                .sum();
        //计算CO超限数
        int coWarnCountSum = minePointInAlarmfoVoList.stream()
                .mapToInt(MinePointInAlarmfoVo::getCoWarnCount)
                .sum();


        //重新对煤矿进行排序 升序
        minePointInAlarmfoVoList.sort(Comparator.comparingInt(MinePointInAlarmfoVo::getMkRank));


        safetyMonitoringVo.setMinePointInAlarmfoList(minePointInAlarmfoVoList);
        safetyMonitoringVo.setPonitSum(pointNumberSum);
        safetyMonitoringVo.setCH4WarnCount(cH4WarnCountSum);
        safetyMonitoringVo.setCoWarnCount(coWarnCountSum);
        safetyMonitoringVo.setCH4Number(ch4Number[0]);
        safetyMonitoringVo.setCoNumber(coNumber[0]);
        return safetyMonitoringVo;

    }


    @Override
    public List<OutLimitAlarmingInfoVO> alarmInfoList(String companyCode,String mineCode) {
        //获取所有煤矿的报警超限数据
        List<OutLimitAlarmingInfoVO> vo = new ArrayList<>();
        //获取所有煤矿
        List<SysOrganization> list = aqjkService.selectCodeUndergroundMiningSubMineList(companyCode,mineCode);

        //去除露天矿
        //魏家峁 150622B0012000210118
        // 铧尖  未知
        // 伊敏  150724B0012000510053
        //20240809 去除 刘园子：621022009406  和  马蹄沟：620824009852
//        List<String> codesToRemove = Arrays.asList("150622B0012000210118", "150724B0012000510053","621022009406","620824009852");
//        list = list.stream()
//                .filter(dto -> !codesToRemove.contains(dto.getOrgCode()))
//                .collect(Collectors.toList());



        for (SysOrganization sysOrganization : list) {
            String orgCode = sysOrganization.getOrgCode();
            List<AqjcYcbjPo>  ycbjList =dwdAqjcYcbjDMapper.selectBJOverrunList(orgCode);
            if (ycbjList.isEmpty()) {
                continue;
            }
            List<OutLimitAlarmingInfoVO> collect = ycbjList.stream().map(t -> {
                OutLimitAlarmingInfoVO outLimitAlarmingInfoVO = new OutLimitAlarmingInfoVO();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                outLimitAlarmingInfoVO.setMineName(sysOrganization.getOrgName());
                outLimitAlarmingInfoVO.setMineCode(orgCode);
                outLimitAlarmingInfoVO.setPointCode(t.getCdbh());
                outLimitAlarmingInfoVO.setAlarmType(t.getYclx());
                //测点类型名称
                outLimitAlarmingInfoVO.setPointTypeName(t.getCgqlxmc());
                outLimitAlarmingInfoVO.setAlarmTypeName("超限报警");
                outLimitAlarmingInfoVO.setPointLocation(t.getCdazwz());
                if (StringUtils.isNotBlank(t.getYckssj())) {
                    try {
                        outLimitAlarmingInfoVO.setAlarmBeginTime(simpleDateFormat.parse(t.getYckssj()));
                    } catch (ParseException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    outLimitAlarmingInfoVO.setAlarmBeginTime(null);
                }
                if (StringUtils.isNotBlank(t.getYcjssj())) {
                    try {
                        outLimitAlarmingInfoVO.setAlarmEndTime(simpleDateFormat.parse(t.getYcjssj()));
                    } catch (ParseException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    outLimitAlarmingInfoVO.setAlarmEndTime(null);
                }
                if (StringUtils.isNotBlank(t.getYckssj()) && StringUtils.isNotBlank(t.getYcjssj())) {
                    //报警时长
                    try {
                        String duration = getDuration(simpleDateFormat.parse(t.getYckssj()), simpleDateFormat.parse(t.getYcjssj()));
                        outLimitAlarmingInfoVO.setAlarmDuration(duration);
                    } catch (ParseException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    outLimitAlarmingInfoVO.setAlarmDuration("");
                }
                if (StringUtils.isNotBlank(t.getYcqjzdz())) {
                    outLimitAlarmingInfoVO.setAlarmMaxValue(new BigDecimal(t.getYcqjzdz()));
                } else {
                    outLimitAlarmingInfoVO.setAlarmMaxValue(null);
                }

                outLimitAlarmingInfoVO.setAlarmCause(t.getYcyy());
                outLimitAlarmingInfoVO.setMeasure(t.getClcs());
                outLimitAlarmingInfoVO.setStatus(StringUtils.isNotBlank(t.getClcs()) ? "完成" : "未完成");
                return outLimitAlarmingInfoVO;
            }).collect(Collectors.toList());
            collect.forEach(volist -> vo.add(volist));
        }
        return vo;
    }

    /**
     * 大屏首页-超员情况
     * @return
     */
    @Override
    public List<OverstaffingSituationDwsVo> getOverstaffingSituation(String companyCode, String mineCode) {
        //获取煤矿 地址灾害类型及核定人数
//        List<MineCodeMapDto> mineCodeMapList = remoteMineInfoService.getMineCodeMapList(null);
        List<DimCoalMineBasicInfoPo> infoPos = dimCoalMineBasicInfoMapper.selectList(new LambdaQueryWrapper<DimCoalMineBasicInfoPo>()
                .eq(DimCoalMineBasicInfoPo::getMiningMethodTypes, "井工矿")
                .eq(StringUtils.isNotBlank(companyCode), DimCoalMineBasicInfoPo::getMqCode, companyCode)
                .eq(StringUtils.isNotBlank(mineCode), DimCoalMineBasicInfoPo::getMkCode, mineCode));

        // 过滤掉煤矿编码为空的记录
        infoPos = infoPos.stream()
                .filter(t -> t.getMkCode() != null && !t.getMkCode().isEmpty())
                .collect(Collectors.toList());

        //排除停产矿井

        //去掉马蹄沟（620824009852）和刘园子煤矿（621022009406）
        List<String> codesToRemove = Arrays.asList("620824009852", "621022009406");
        infoPos = infoPos.stream()
                .filter(t -> !codesToRemove.contains(t.getMkCode()))
                .collect(Collectors.toList());


        // 按照 mkRank 排序
        List<DimCoalMineBasicInfoPo> sortedList = infoPos.stream()
                .sorted(Comparator.nullsLast(Comparator.comparing(DimCoalMineBasicInfoPo::getMkRank)))
                .collect(Collectors.toList());




        List<OverstaffingSituationDwsVo> vos = sortedList.stream().map(t -> {
            OverstaffingSituationDwsVo vo = new OverstaffingSituationDwsVo();
            //获取当前煤矿井下人数
            Integer personNumber =dwdRydwRyssHMapper.selectPersonNumberList(t.getMkCode());
            vo.setMineCode(t.getMkCode());
            vo.setMineName(t.getMkFullName());
            //灾害类型
            vo.setHazardType(t.getMineDisasterTypes());
            //矿井核定人数
            vo.setMineMaxPeopleNumber(Integer.parseInt(t.getApprovedPersonCapacityQty()));
            vo.setNowNumber(personNumber);
            //预警状态
            String state = null;
            //核定人数-实时人数 大于等于零  正常
            if (Optional.ofNullable(vo.getMineMaxPeopleNumber()).orElse(0)- vo.getNowNumber() >= 0) {
                state = "正常";
            } else {
                state = "超员";
            }
            vo.setWarningState(state);
            return vo;
        }).collect(Collectors.toList());
        return vos;
    }

    /**
     * 大屏首页-人员检测
     * @return
     */
    @Override
    public PersonnelMonitoringVo getPersonnelMonitoring(String companyCode, String mineCode) {
        PersonnelMonitoringVo vo=new PersonnelMonitoringVo();

        //获取所有煤矿
        List<SysOrganization> list = aqjkService.selectCodeSubMineList(companyCode,mineCode);


        //20240821 去除 刘园子：621022009406  和  马蹄沟：620824009852
//        List<String> codesToRemove1 = Arrays.asList("621022009406","620824009852");
//        list = list.stream()
//                .filter(dto -> !codesToRemove1.contains(dto.getOrgCode()))
//                .collect(Collectors.toList());
        //露天矿
        //魏家峁 150622B0012000210118
        // 铧尖  未知
        // 伊敏  150724B0012000510053
//        List<String> codesToRemove = Arrays.asList("150622B0012000210118", "150724B0012000510053");
        //露天矿编码集合
        List<String> codesToRemove = new ArrayList<>();
        //获取露天矿 并将露天矿编码放入集合中
        List<SysOrganization> stripMineList = aqjkService.selectCodeOutdoorsSubMineList();
        stripMineList.forEach(loutiankuang->{
            codesToRemove.add(loutiankuang.getOrgCode());
        });



        // 初始化计数器，初始计数为
//        CountDownLatch countDownLatch = new CountDownLatch(list.size());

        List<MineLeaderInfoVo> vos = list.stream().map(t -> {
//        new Thread(()->{
//            try {
            //判断是否是露天矿
            Boolean isStripMine = false;
            if (codesToRemove.contains(t.getOrgCode())) {
                //此煤矿编码属于露天煤矿
                isStripMine = true;
            }

            MineLeaderInfoVo leaderInfoVo = new MineLeaderInfoVo();
            //获取当前煤矿井下人数
            Integer personNumber = 0;
            if (isStripMine) {
                //露天
                personNumber= dwdLtkClrydwSssjHMapper.selectPersonNumberList(t.getOrgCode());
            } else {
                //井工
                personNumber =dwdRydwRyssHMapper.selectPersonNumberList(t.getOrgCode());
            }

            leaderInfoVo.setMineCode(t.getOrgCode());
            leaderInfoVo.setMineName(t.getOrgName());

            leaderInfoVo.setMineNowNumber(personNumber);


            //获取帆软带值班领导信息
            //值班领导名称集合
            TreeSet<String> duty = new TreeSet<>();
            //带班领导名称集合
            TreeSet<String> shift = new TreeSet<>();
            //获取帆软煤矿名称
            List<JyglDwmcEntityPo> fineListByCode = this.getFineListByCode(t.getOrgCode());
            //有数据  且三级煤矿名称不为空
            if (fineListByCode != null && fineListByCode.size() > 0 && fineListByCode.get(0).getFourdw() != null) {
                //帆软煤矿名称
                String mineName = fineListByCode.get(0).getFourdw();
                //获取班次时间
                List<JyglInsertShiftManage1Po> fineDataClassListBymineName = this.getFineDataClassListBymineName(mineName);
                //获取带值班表
                List<JyglShiftManagementPo> fineDataBeOnWatchListBymineName = this.getFineDataBeOnWatchListBymineName(mineName);
                //判断值班是否是 全天
                Boolean dutyIsAllDay = false;
                for (JyglShiftManagementPo tt : fineDataBeOnWatchListBymineName) {//值班类型  有值 并且是全天
                    if (tt.getClasses1() != null && "全天".equals(tt.getClasses1())) {
                        dutyIsAllDay = true;
                        break; // 提前结束循环
                    }
                }


                if (dutyIsAllDay) {
                    // 值班是全天
                    for (JyglShiftManagementPo tt : fineDataBeOnWatchListBymineName) {//值班类型  有值 并且是全天
                        if (StringUtils.isNotBlank(tt.getLeader1())) {
                            duty.add(tt.getLeader1());
                        }
                    }
                    //赋值班次
                    leaderInfoVo.setDutyClass("全天");

                } else {
                    //区分 早班 中班 晚班  后夜班
                    //早班开始时间
                    List<String> morningTime = new ArrayList<>();
                    //中班开始时间
                    List<String> middleTime = new ArrayList<>();
                    //晚班开始时间
                    List<String> nightTime = new ArrayList<>();
                    //后夜班开始时间
                    List<String> afterNightTime = new ArrayList<>();

                    if (!fineDataClassListBymineName.isEmpty()) {
                        if (StringUtils.isNotBlank(fineDataClassListBymineName.get(0).getMornStart()) && StringUtils.isNotBlank(fineDataClassListBymineName.get(0).getMornStop())){
                            morningTime.add(fineDataClassListBymineName.get(0).getMornStart());
                            morningTime.add(fineDataClassListBymineName.get(0).getMornStop());
                        }
                        if (StringUtils.isNotBlank(fineDataClassListBymineName.get(0).getMidStart()) && StringUtils.isNotBlank(fineDataClassListBymineName.get(0).getMidStop())){
                            middleTime.add(fineDataClassListBymineName.get(0).getMidStart());
                            middleTime.add(fineDataClassListBymineName.get(0).getMidStop());
                        }
                        if (StringUtils.isNotBlank(fineDataClassListBymineName.get(0).getEvenStart()) && StringUtils.isNotBlank(fineDataClassListBymineName.get(0).getEvenStop())){
                            nightTime.add(fineDataClassListBymineName.get(0).getEvenStart());
                            nightTime.add(fineDataClassListBymineName.get(0).getEvenStop());
                        }
                        if (StringUtils.isNotBlank(fineDataClassListBymineName.get(0).getEvenLstart()) && StringUtils.isNotBlank(fineDataClassListBymineName.get(0).getEvenLstop())) {
                            afterNightTime.add(fineDataClassListBymineName.get(0).getEvenLstart());
                            afterNightTime.add(fineDataClassListBymineName.get(0).getEvenLstop());
                        }
                    }
                    //时间段集合
                    Map<String, List<String>> clases = new HashMap<>();
                    clases.put("早", morningTime);
                    clases.put("中", middleTime);
                    clases.put("夜", nightTime);
                    clases.put("后夜", afterNightTime);
                    //判断现在时间是数据那个班
                    String nowTime = DateUtils.format(new Date(), "HH:mm");
                    String dutyclass1 = this.determineShift(nowTime, clases);
                    // 使用 Java Stream 过滤出包含 classes2 包含 "早班" 的集合
                    //赋值班次
                    leaderInfoVo.setDutyClass(dutyclass1);
                    //将所有的值班领导放入集合中
                    List<JyglShiftManagementPo> filteredList = fineDataBeOnWatchListBymineName.stream()
                            .filter(po -> po.getClasses1() != null && po.getClasses1().contains(dutyclass1))
                            .collect(Collectors.toList());
                    //遍历集合  值班查出当前班次所有领导集合
                    filteredList.forEach(po -> {
                        if (StringUtils.isNotBlank(po.getLeader1())) {
                            //领导不是空的
                            duty.add(po.getLeader1());
                        }
                    });
                }


                //帆软带班领导 名称集合 获取带班名称
//                fineDataBeOnWatchListBymineName.forEach(tt -> {
//                    //获取所有的带班领导 区分早中晚夜班
//                    //获取当前班次
//
//                    if (StringUtils.isNotBlank(tt.getLeader2())) {
//                        //领导不是空的
//                        shift.add(tt.getLeader2());
//                    }
//                });
                //判断带班是否是 全天
                Boolean shiftIsAllDay = false;
                for (JyglShiftManagementPo tt : fineDataBeOnWatchListBymineName) {//值班类型  有值 并且是全天
                    if (tt.getClasses2() != null && "全天".equals(tt.getClasses2())) {
                        shiftIsAllDay = true;
                        break; // 提前结束循环
                    }
                }

                if (shiftIsAllDay) {
                    // 带班是全天
                    for (JyglShiftManagementPo tt : fineDataBeOnWatchListBymineName) {//值班类型  有值 并且是全天
                        if (StringUtils.isNotBlank(tt.getLeader2())) {
                            shift.add(tt.getLeader2());
                        }
                    }
                    //赋值班次
                    leaderInfoVo.setShiftClass("全天");

                } else {
                    //值班不是全天  区分早 中 晚 夜
                    //获取带班班次
                    if (fineDataClassListBymineName != null && !fineDataClassListBymineName.isEmpty()) {
                        JyglInsertShiftManage1Po jyglInsertShiftManage1Po = fineDataClassListBymineName.get(0);
                        if (jyglInsertShiftManage1Po != null) {
                            //有时间段
                            String shiftClass = dwdRydwService.getShiftTimeList(new Date(), jyglInsertShiftManage1Po);
                            if (StringUtils.isNotEmpty(shiftClass)) {
                                leaderInfoVo.setShiftClass(shiftClass);
                                TreeSet<String> minShiftListByClasses = dwdRydwService.getMinShiftListByClasses(fineDataBeOnWatchListBymineName, shiftClass);
                                minShiftListByClasses.forEach(ss -> shift.add(ss));
                            } else {
                                //无时间段 放入所有的带班
                                for (JyglShiftManagementPo tt : fineDataBeOnWatchListBymineName) {//值班类型  有值 并且是全天
                                    if (StringUtils.isNotBlank(tt.getLeader2())) {
                                        shift.add(tt.getLeader2());
                                    }
                                }
                                leaderInfoVo.setShiftClass(null);
                            }
                        } else {
                            //无时间段
                        }
                    }else{
                        //无时间段 放入所有的带班
                        for (JyglShiftManagementPo tt : fineDataBeOnWatchListBymineName) {//值班类型  有值 并且是全天
                            if (StringUtils.isNotBlank(tt.getLeader2())) {
                                shift.add(tt.getLeader2());
                            }
                        }
                    }

                }


            }


            //获取dws井下带班领导入井信息
            List<LeadVo> leads = dwdRydwRyssHMapper.selectLeadPitInfo(t.getOrgCode());
            //备份井下领导数据
            List<LeadVo> remark = new ArrayList<>();
            leads.forEach(s->{
                remark.add(s);
            });

            //dws 精准人员定位获取的矿领导与帆软填报带班领导求交集
            //如果存在相同的姓名则需要 否则将剔除
            leads.removeIf(tt -> !shift.contains(tt.getName()));

            //补充领导基本信息
            List<LeadInfoDto> leadInfoDtos = leads.stream().map(tt -> {
                LeadInfoDto leadInfoDto = new LeadInfoDto();
                BeanUtils.copyProperties(tt, leadInfoDto);
                //获取人员信息
                RydwRyxxPo rydwRyxxPo=dwdRydwRyxxDMapper.selectMaxDateInfo(t.getOrgCode(), leadInfoDto.getCode());
                if (rydwRyxxPo != null) {
                    //职务
                    leadInfoDto.setPosition(rydwRyxxPo.getZw());
                    //部门名称
                    leadInfoDto.setDeptName(rydwRyxxPo.getDzbzbm());
                } else {
                    leadInfoDto.setPosition("---");
                    leadInfoDto.setDeptName("---");
                }

                return leadInfoDto;
            }).collect(Collectors.toList());

            //带班领导姓名
            //数据不为空
//            leads.forEach(m -> {
//                if (StringUtils.isBlank(leaderInfoVo.getShiftLeader())) {
//                    //是空的 第一次 追加
//                    leaderInfoVo.setShiftLeader(m.getName());
//                } else {
//                    //第二次 追加 前面携带逗号
//                    leaderInfoVo.setShiftLeader(leaderInfoVo.getShiftLeader() + "," + m.getName());
//                }
//            });
            //仅使用帆软带班领导名称返回
            shift.forEach(shiftDemp->{
                if (StringUtils.isBlank(leaderInfoVo.getShiftLeader())) {
                    //是空的 第一次 追加
                    leaderInfoVo.setShiftLeader(shiftDemp);
                } else {
                    //第二次 追加 前面携带逗号
                    leaderInfoVo.setShiftLeader(leaderInfoVo.getShiftLeader() + "," + shiftDemp);
                }
            });

            leaderInfoVo.setLeaderInfo(leadInfoDtos);


            //帆软值班领导
            AtomicReference<String> dutyString = new AtomicReference<>("");
            duty.forEach(tt -> {
                if (StringUtils.isBlank(dutyString.get())) {
                    //是空的 第一次 追加
                    dutyString.set(tt);
                } else {
                    //第二次 追加 前面携带逗号
                    dutyString.set(dutyString.get() + "," + tt);
                }
            });
            //设置值班领导
            leaderInfoVo.setDutyLeader(dutyString.get());

            //实际井下矿领导  读取所有姓名放入备注里面
            AtomicReference<String> remarkLeaderString = new AtomicReference<>("");
            remark.forEach(tt -> {
                if (StringUtils.isBlank(remarkLeaderString.get())) {
                    //是空的 第一次 追加
                    remarkLeaderString.set(tt.getName());
                } else {
                    //第二次 追加 前面携带逗号
                    remarkLeaderString.set(remarkLeaderString.get()+ "," + tt.getName());
                }
            });
            //存放备注
            leaderInfoVo.setRemark("DWS井下领导名称集合：" + remarkLeaderString.get());
            return leaderInfoVo;


        }).collect(Collectors.toList());


        //总人数
        // 计算总人数
        int totalMineNowNumber = vos.stream()
                .mapToInt(MineLeaderInfoVo::getMineNowNumber)  // 提取每个对象的现有人数
                .sum();  // 对现有人数进行求和


        //计算带班领导数
        int sum = 0;
        for (MineLeaderInfoVo mineLeaderInfoVo : vos) {
            //遍历所有煤矿带班领导
            if ( StringUtils.isNotEmpty(mineLeaderInfoVo.getShiftLeader())){
                //带班字段不为空
                String shiftLeader = mineLeaderInfoVo.getShiftLeader();
                if (shiftLeader.contains(",")) {
                    //存在逗号
                    String[] split = shiftLeader.split(",");
                    for (String s : split) {
                        sum++;
                    }
                } else {
                    //不存在逗号   直接加 1
                    sum++;
                }
            }
        }
        //带班领导数
        vo.setShiftLeaderNumber(sum);
        //总人数
        vo.setLeaderSum(totalMineNowNumber);


        //井下人数  downholeMan;
        //（去除露天矿）
        List<MineLeaderInfoVo> downholeManVos = vos.stream()
                .filter(dto -> !codesToRemove.contains(dto.getMineCode()))
                .collect(Collectors.toList());
        int downholeMan = downholeManVos.stream()
                .mapToInt(MineLeaderInfoVo::getMineNowNumber)  // 提取每个对象的现有人数
                .sum();  // 对现有人数进行求和

        // 坑下人数 pitDownMan;
        //（仅有露天矿） 魏家峁 铧尖 伊敏
        List<MineLeaderInfoVo> pitDownManVos = vos.stream()
                .filter(dto -> codesToRemove.contains(dto.getMineCode()))
                .collect(Collectors.toList());
        int pitDownMan = pitDownManVos.stream()
                .mapToInt(MineLeaderInfoVo::getMineNowNumber)  // 提取每个对象的现有人数
                .sum();  // 对现有人数进行求和


        //坑下人数
        vo.setPitDownMan(pitDownMan);
        //井下人数
        vo.setDownholeMan(downholeMan);
        //煤矿领导及人数信息列表
        vo.setMineLeaderInfoList(vos);
        return vo;

    }

    /**
     * 人员入井后轨迹
     * @param staffCode
     * @param inTime
     * @param mineCode
     * @return
     */
    @Override
    public List<TrailVo> trail(String staffCode, String inTime, String mineCode) {
        List<TrailVo> vos = new ArrayList<>();

        //查询实时表  获取实时表内人员信息
        RydwRyssPo rydwRyssPo = dwdRydwRyssHMapper.selectTrail(staffCode, inTime, mineCode);
        if (rydwRyssPo == null) {
            return new ArrayList<>();
        }
        //查询当前煤矿下所有基站
        List<RydwRyjzPo> rydwRyjzPos = dwdRydwRyjzDMapper.selectStationListByMineCode(mineCode);
        //转成map
        Map<String, RydwRyjzPo> rydwRyjzPoMap = rydwRyjzPos.stream()
                .collect(Collectors.toMap(
                        RydwRyjzPo::getJzbm, // 键为 jzbm 属性
                        p -> Optional.ofNullable(p).orElse(new RydwRyjzPo()), // 值为 RydwRyjzPo 对象，处理可能为空的情况
                        (existing, replacement) -> existing)); // 解决重复键冲突的策略，保留已存在的值

        //获取的轨迹字段集合
        String xjgjjzsjjh = rydwRyssPo.getXjgjjzsjjh();
        //根据逗号拆分 每一个分站
        String[] split = xjgjjzsjjh.split(",");
        for (String s : split) {
            TrailVo trailVo = new TrailVo();
            //根据& 区分编码和时间
            String[] split1 = s.split("&");
            String stationCode = split1[0];
            String inStationCodeTime = split1[1];
            //获取分站详情
            RydwRyjzPo rydwRyjzPo = rydwRyjzPoMap.get(stationCode);
            trailVo.setSubstationCode(stationCode);
            trailVo.setInTime(inStationCodeTime);
            if (rydwRyjzPo != null) {
                trailVo.setSubstationName(rydwRyjzPo.getJzmc() + "_" + rydwRyjzPo.getWzzs());
                trailVo.setCoordinate_x(rydwRyjzPo.getXzb());
                trailVo.setCoordinate_y(rydwRyjzPo.getYzb());
                trailVo.setCoordinate_z(rydwRyjzPo.getZzb());
            } else {
                trailVo.setSubstationName(stationCode);
                trailVo.setCoordinate_x("0");
                trailVo.setCoordinate_y("0");
                trailVo.setCoordinate_z("0");
            }
            vos.add(trailVo);
        }

        // 倒序操作
//        Collections.reverse(vos);

        return vos;
    }

    /**
     * 数据查询-安全监控-实时数据
     * @param pageQuery
     * @param type
     * @param status
     * @return
     */
    @Override
    public ResponsePage<DwdAqjcCdssHVo> aqjkNowDataList(PageQuery pageQuery, String type, String status, String companyCode, String mineCode) {
        if (pageQuery.getPageNum() == null) {
            pageQuery.setPageNum(0);
        }
        if (pageQuery.getPageSize() == null) {
            pageQuery.setPageSize(10);
        }
        pageQuery.setPageNum(pageQuery.getPageNum() >= 1 ? pageQuery.getPageNum() * pageQuery.getPageSize():0);
        List<String> mineCodeList = new ArrayList<>();
        List<SysOrganization> mineCodeListByCompanyCode = new ArrayList<>();
        if (StringUtils.isNotEmpty(companyCode) && StringUtils.isEmpty(mineCode)) {
            //获取当前公司的所有煤矿
             mineCodeListByCompanyCode = aqjkService.getMineCodeListByCompanyCode(companyCode);
            for (int i = 0; i < mineCodeListByCompanyCode.size(); i++) {
                SysOrganization org = mineCodeListByCompanyCode.get(i);
                mineCodeList.add(org.getOrgCode());
            }
        }

        if (StringUtils.isNotEmpty(mineCode)) {
            mineCodeList = null;
        }
        //字典转义
        if (StringUtils.isNotEmpty(type)) {
            List<SysDictData> redisType = RedisUtils.getCacheObject(Constants.SYS_DICT_KEY+"aqjk_sensor_type");
            for (SysDictData t : redisType) {
                if (type.equals(t.getDictValue())) {
                    type = t.getDictLabel();
                    break;
                }
            }
        }
        //查询安全监控实时数据
        List<DwdAqjcCdssHVo> list= new ArrayList<>();
        if (StringUtils.isNotEmpty(mineCode)) {
            // 有煤矿编码查询当前煤矿煤矿最新数据
            list= dwdAqjcCdssHMapper.aqjkNowDataListByMineCode(pageQuery, type, status,  mineCode);
        } else {
            list= dwdAqjcCdssHMapper.aqjkNowDataList(pageQuery, type, status, mineCodeList,  mineCode);
        }

        if (list.isEmpty()) {
            return new ResponsePage<>(new ArrayList(), 0);
        }
        //获取所有煤矿列表
        List<DimCoalMineBasicInfoPo> mineList = aqjkService.selectCodeSubMineInfoList();
        Map<String, DimCoalMineBasicInfoPo> collect = mineList.stream()
                .collect(Collectors.toMap(DimCoalMineBasicInfoPo::getMkCode, org -> org));

        list.forEach(t->{
            String mkbm = t.getMkbm();
            DimCoalMineBasicInfoPo dimCoalMineBasicInfoPo = collect.get(mkbm);
            if (dimCoalMineBasicInfoPo != null) {
                t.setMineCode(t.getMkbm());
                t.setMineName(dimCoalMineBasicInfoPo.getMkFullName());
                t.setCompanyCode(dimCoalMineBasicInfoPo.getMqCode());
                t.setCompanyName(dimCoalMineBasicInfoPo.getMqFullName());
            }
        });

        return new ResponsePage<>(list, list.get(0).getTotal());
    }

    /**
     * 数据查询-安全监控-历史数据
     * @param pageQuery
     * @param type
     * @param location
     * @param companyCode
     * @param mineCode
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public ResponsePage<DwdAqjcCdssDVo> aqjkHisDataList(PageQuery pageQuery, String type, String location, String companyCode, String mineCode, Date startTime, Date endTime) {
        if (pageQuery.getPageNum() == null) {
            pageQuery.setPageNum(0);
        }
        if (pageQuery.getPageSize() == null) {
            pageQuery.setPageSize(10);
        }
        if (startTime == null) {
            //一小时的前
            startTime= net.hn.hnms.sys.common.core.utils.DateUtils.addHours(new Date(), -1);
        }
        if (endTime == null) {
            endTime = new Date();
        }
        pageQuery.setPageNum(pageQuery.getPageNum() >= 1 ? pageQuery.getPageNum() * pageQuery.getPageSize():0);
        List<String> mineCodeList = new ArrayList<>();
        if (StringUtils.isNotEmpty(companyCode) && StringUtils.isEmpty(mineCode)) {
            //获取当前公司的所有煤矿
            List<SysOrganization> mineCodeListByCompanyCode = aqjkService.getMineCodeListByCompanyCode(companyCode);

            for (int i = 0; i < mineCodeListByCompanyCode.size(); i++) {
                SysOrganization org = mineCodeListByCompanyCode.get(i);
                mineCodeList.add(org.getOrgCode());
            }
        }
        if (StringUtils.isNotEmpty(mineCode)) {
            mineCodeList = null;
        }
        //字典转义
        if (StringUtils.isNotEmpty(type)) {
            List<SysDictData> redisType = RedisUtils.getCacheObject(Constants.SYS_DICT_KEY+"aqjk_sensor_type");
            for (SysDictData t : redisType) {
                if (type.equals(t.getDictValue())) {
                    type = t.getDictLabel();
                    break;
                }
            }
        }
        //查询安全监控历史数据
        List<DwdAqjcCdssDVo> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(mineCode)) {
            // 有煤矿编码查询当前煤矿煤矿最新数据
            list= dwdAqjcCdssDMapper.aqjkHisDataListByMineCode(pageQuery, type, location, startTime, endTime, mineCode);
        } else {
            list= dwdAqjcCdssDMapper.aqjkHisDataList(pageQuery, type, location, startTime, endTime, mineCodeList,  mineCode);
        }
        if (list.isEmpty()) {
            return new ResponsePage<>(new ArrayList(), 0);
        }
        //获取所有煤矿列表
        List<DimCoalMineBasicInfoPo> mineList = aqjkService.selectCodeSubMineInfoList();
        Map<String, DimCoalMineBasicInfoPo> collect = mineList.stream()
                .collect(Collectors.toMap(DimCoalMineBasicInfoPo::getMkCode, org -> org));

        list.forEach(t->{
            String mkbm = t.getMkbm();
            DimCoalMineBasicInfoPo dimCoalMineBasicInfoPo = collect.get(mkbm);
            if (dimCoalMineBasicInfoPo != null) {
                t.setMineCode(t.getMkbm());
                t.setMineName(dimCoalMineBasicInfoPo.getMkFullName());
                t.setCompanyCode(dimCoalMineBasicInfoPo.getMqCode());
                t.setCompanyName(dimCoalMineBasicInfoPo.getMqFullName());
            }
        });
        return new ResponsePage<>(list, list.get(0).getTotal());

    }

    /**
     * 数据查询-安全监控-测点信息
     * @param pageQuery
     * @param type
     * @param location
     * @param companyCode
     * @param mineCode
     * @return
     */
    @Override
    public ResponsePage<DwdAqjcCdssDVo> aqjkPointDataList(PageQuery pageQuery, String type, String location, String companyCode, String mineCode) {
        if (pageQuery.getPageNum() == null) {
            pageQuery.setPageNum(0);
        }
        if (pageQuery.getPageSize() == null) {
            pageQuery.setPageSize(10);
        }
        pageQuery.setPageNum(pageQuery.getPageNum() >= 1 ? pageQuery.getPageNum() * pageQuery.getPageSize():0);
        List<String> mineCodeList = new ArrayList<>();
        if (StringUtils.isNotEmpty(companyCode) && StringUtils.isEmpty(mineCode)) {
            //获取当前公司的所有煤矿
            List<SysOrganization> mineCodeListByCompanyCode = aqjkService.getMineCodeListByCompanyCode(companyCode);

            for (int i = 0; i < mineCodeListByCompanyCode.size(); i++) {
                SysOrganization org = mineCodeListByCompanyCode.get(i);
                mineCodeList.add(org.getOrgCode());
            }
        }
        if (StringUtils.isNotEmpty(mineCode)) {
            mineCodeList = null;
        }
        //字典转义
//        if (StringUtils.isNotEmpty(type)) {
//            List<SysDictData> redisType = RedisUtils.getCacheObject(Constants.SYS_DICT_KEY+"aqjk_sensor_type");
//            for (SysDictData t : redisType) {
//                if (type.equals(t.getDictValue())) {
//                    type = t.getDictLabel();
//                    break;
//                }
//            }
//        }
        List<DwdAqjcCddyDVo> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(mineCode)) {
            //数据查询-安全监控-测点信息
            list=dwdAqjcCddyDMapper.aqjkPointDataListByMineCode(pageQuery, type, location, mineCode);
        } else {
            //数据查询-安全监控-测点信息
            list=dwdAqjcCddyDMapper.aqjkPointDataList(pageQuery, type, location, mineCodeList, mineCode);

        }

        if (list.isEmpty()) {
            return new ResponsePage<>(new ArrayList(), 0);
        }
        //获取所有煤矿列表
        List<DimCoalMineBasicInfoPo> mineList = aqjkService.selectCodeSubMineInfoList();
        Map<String, DimCoalMineBasicInfoPo> collect = mineList.stream()
                .collect(Collectors.toMap(DimCoalMineBasicInfoPo::getMkCode, org -> org));

        list.forEach(t->{
            String mkbm = t.getMkbm();
            DimCoalMineBasicInfoPo dimCoalMineBasicInfoPo = collect.get(mkbm);
            if (dimCoalMineBasicInfoPo != null) {
                t.setMineCode(t.getMkbm());
                t.setMineName(dimCoalMineBasicInfoPo.getMkFullName());
                t.setCompanyCode(dimCoalMineBasicInfoPo.getMqCode());
                t.setCompanyName(dimCoalMineBasicInfoPo.getMqFullName());
            }
        });
        return new ResponsePage<>(list, list.get(0).getTotal());
    }

    /**
     * 数据查询-安全监控-报警明细
     * @param pageQuery
     * @param type
     * @param alarmType
     * @param companyCode
     * @param mineCode
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public ResponsePage<DwdAqjcYcbjDVo> aqjkAlarmDataList(PageQuery pageQuery, String type, String alarmType, String companyCode, String mineCode, Date startTime, Date endTime) {
        if (pageQuery.getPageNum() == null) {
            pageQuery.setPageNum(0);
        }
        if (pageQuery.getPageSize() == null) {
            pageQuery.setPageSize(10);
        }
        if (startTime == null) {
            //一小时的前
            startTime= net.hn.hnms.sys.common.core.utils.DateUtils.addHours(new Date(), -1);
        }
        if (endTime == null) {
            endTime = new Date();
        }

        pageQuery.setPageNum(pageQuery.getPageNum() >= 1 ? pageQuery.getPageNum() * pageQuery.getPageSize():0);
        List<String> mineCodeList = new ArrayList<>();
        if (StringUtils.isNotEmpty(companyCode) && StringUtils.isEmpty(mineCode)) {
            //获取当前公司的所有煤矿
            List<SysOrganization> mineCodeListByCompanyCode = aqjkService.getMineCodeListByCompanyCode(companyCode);

            for (int i = 0; i < mineCodeListByCompanyCode.size(); i++) {
                SysOrganization org = mineCodeListByCompanyCode.get(i);
                mineCodeList.add(org.getOrgCode());
            }
        }
        if (StringUtils.isNotEmpty(mineCode)) {
            mineCodeList = null;
        }
        //字典转义
        if (StringUtils.isNotEmpty(type)) {
            List<SysDictData> redisType = RedisUtils.getCacheObject(Constants.SYS_DICT_KEY+"aqjk_sensor_type");
            for (SysDictData t : redisType) {
                if (type.equals(t.getDictValue())) {
                    type = t.getDictLabel();
                    break;
                }
            }
        }
        List<DwdAqjcYcbjDVo> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(mineCode)) {
            //数据查询-安全监控-报警明细
            list=dwdAqjcYcbjDMapper.aqjkAlarmDataListByMineCode(pageQuery, type, alarmType, mineCode, startTime, endTime);
        } else {
            //数据查询-安全监控-报警明细
            list=dwdAqjcYcbjDMapper.aqjkAlarmDataList(pageQuery, type, alarmType, mineCodeList, mineCode, startTime, endTime);
        }

        if (list.isEmpty()) {
            return new ResponsePage<>(new ArrayList(), 0);
        }
        //获取所有煤矿列表
        List<DimCoalMineBasicInfoPo> mineList = aqjkService.selectCodeSubMineInfoList();
        Map<String, DimCoalMineBasicInfoPo> collect = mineList.stream()
                .collect(Collectors.toMap(DimCoalMineBasicInfoPo::getMkCode, org -> org));

        list.forEach(t->{
            String mkbm = t.getMkbm();
            DimCoalMineBasicInfoPo dimCoalMineBasicInfoPo = collect.get(mkbm);
            if (dimCoalMineBasicInfoPo != null) {
                t.setMineCode(t.getMkbm());
                t.setMineName(dimCoalMineBasicInfoPo.getMkFullName());
                t.setCompanyCode(dimCoalMineBasicInfoPo.getMqCode());
                t.setCompanyName(dimCoalMineBasicInfoPo.getMqFullName());
            }
            //计算报警时长
            Date alarmEndDateTime = null;
            Date alarmStartDateTime = null;

            try {
                if (StringUtils.isEmpty(t.getYcjssj())) {
                    alarmEndDateTime = new Date();
                } else {
                    alarmEndDateTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(t.getYcjssj());
                }
                alarmStartDateTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(t.getYckssj());
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            String duration = this.getDuration(alarmStartDateTime, alarmEndDateTime);
            t.setAlarmDuration(duration);
        });
        return new ResponsePage<>(list, list.get(0).getTotal());
    }

    /**
     * 数据查询-测点值时间图
     * @param pointCode
     * @param startTime
     * @param endTime
     * @param mineCode
     * @return
     */
    @Override
    public PointDateListVo trendByPointCode(String pointCode, Date startTime, Date endTime, String mineCode) {
        List<DwdAqjcCdssDVo> list = dwdAqjcCdssDMapper.trendByPointCode(pointCode, startTime, endTime, mineCode);
        PointDateListVo vo = new PointDateListVo();
        List<String> pointValueList = new ArrayList<>();
        List<String> DateList = new ArrayList<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat dateFormatString = new SimpleDateFormat("MM-dd HH:mm:ss");

        list.forEach(t->{
            pointValueList.add(t.getCdz());
            try {
                Date parse = dateFormat.parse(t.getSjsj());
                String format = dateFormatString.format(parse);
                DateList.add(format);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        });
        vo.setDateList(DateList);
        vo.setPointValueList(pointValueList);
        return vo;
    }

    @Override
    public Ch4AndCoOverrunVo getCh4AndCoOverrunVo(String mineCode) {
        Ch4AndCoOverrunVo ch4AndCoOverrunVo = new Ch4AndCoOverrunVo();

        //一氧化碳报警
        Integer coWarnCount = dwdAqjcCdssHMapper.selectCoWarnCount(mineCode);
        ch4AndCoOverrunVo.setCoOverrunNumber(coWarnCount.toString());
        //甲烷报警
        Integer ch4WarnCount = dwdAqjcCdssHMapper.selectCH4WarnCount(mineCode);
        ch4AndCoOverrunVo.setCh4OverrunNumber(ch4WarnCount.toString());
        return ch4AndCoOverrunVo;
    }

    /**
     * 根据煤矿编码获取有效生产时长列表
     * @param mineCode
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public List<EffectiveProductionTimeByMineCodeDto> getEffectiveProductionTimeByMineCode(String mineCode, Date startTime, Date endTime) {
        if (startTime == null) {
            // 获取当前日期的 LocalDate
            LocalDate today = LocalDate.now();

            // 将 LocalDateTime 转换为 Date
            startTime = Date.from(today.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
            System.out.println("startOfDay = " + startTime);
        }
        if (endTime == null) {
            LocalDate today = LocalDate.now();
            endTime = Date.from(today.plusDays(1).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
            System.out.println("today = " + endTime);
        }
        List<DwdCoalMineProduceDurationRtDPo> dwdCoalMineProduceDurationRtDPos = dwdCoalMineProduceDurationRtDMapper.selectList(new LambdaQueryWrapper<DwdCoalMineProduceDurationRtDPo>()
                .eq(DwdCoalMineProduceDurationRtDPo::getMkbm, mineCode)
                .gt(DwdCoalMineProduceDurationRtDPo::getStatusTime, startTime)
                .le(DwdCoalMineProduceDurationRtDPo::getStatusTime, endTime)
                .orderByAsc(DwdCoalMineProduceDurationRtDPo::getStatusTime));
        if (dwdCoalMineProduceDurationRtDPos == null) {
            return new ArrayList<>();
        }

        List<EffectiveProductionTimeByMineCodeDto> vo = new ArrayList<>();
        //初始状态
        Integer status = null;
        Date start_temp = null;
        Date end_temp = null;
        //获取第一个状态
        for (int i = 0; i < dwdCoalMineProduceDurationRtDPos.size(); i++) {
            DwdCoalMineProduceDurationRtDPo t = dwdCoalMineProduceDurationRtDPos.get(i);
            if (status == null) {
                status = t.getStatus();
                start_temp = startTime;
                end_temp = t.getStatusTime();
            }

            if (end_temp.before(t.getStatusTime())) {
                if (status != t.getStatus()) {
                    end_temp = t.getStatusTime();
                    //收集一次时间
                    EffectiveProductionTimeByMineCodeDto dto = new EffectiveProductionTimeByMineCodeDto();
                    dto.setStartTime(start_temp);
                    dto.setEndTime(end_temp);
                    dto.setDuration((end_temp.getTime() - start_temp.getTime())/1000);
                    dto.setStatus(status);
                    //状态发生了改变
                    status = t.getStatus();
                    //开始时间变成了结束时间
                    start_temp = t.getStatusTime();
                    ;
                    vo.add(dto);
                }
            }
            // 判断是否是最后一个元素
            if (i == dwdCoalMineProduceDurationRtDPos.size() - 1) {
                //如果最后一个状态是0 则追加结尾
                if (status == 0) {
                    EffectiveProductionTimeByMineCodeDto dto = new EffectiveProductionTimeByMineCodeDto();
                    dto.setStartTime(start_temp);
                    dto.setEndTime(endTime);
                    dto.setDuration((endTime.getTime() - start_temp.getTime()) / 1000);
                    dto.setStatus(status);
                    vo.add(dto);
                } else {
                    //是1 则补充两个状态
                    EffectiveProductionTimeByMineCodeDto dto = new EffectiveProductionTimeByMineCodeDto();
                    dto.setStartTime(start_temp);
                    dto.setEndTime(t.getStatusTime());
                    dto.setDuration((t.getStatusTime().getTime() - start_temp.getTime()) / 1000);
                    dto.setStatus(status);
                    vo.add(dto);

                    EffectiveProductionTimeByMineCodeDto dto1 = new EffectiveProductionTimeByMineCodeDto();
                    dto1.setStartTime(t.getStatusTime());
                    dto1.setEndTime(endTime);
                    dto1.setDuration((endTime.getTime() - t.getStatusTime().getTime()) / 1000);
                    //如果开始时间和结束时间在五分钟之内则补1  否则补零
                    if (endTime.getTime()-t.getStatusTime().getTime()  < 300000) {
                        dto1.setStatus(1);
                    } else {
                        dto1.setStatus(0);
                    }
                    vo.add(dto1);
                }
            }

        }
        vo.forEach(System.out::println);
        return vo;
    }

    /**
     * 根据煤矿编码和天数获取有效生产时长统计
     * @param mineCode
     * @param day
     * @return
     */
    @Override
    public CurveVo getEffectiveProductionTimeByMineCodeAndDay(String mineCode, String day) {
        CurveVo vo = new CurveVo();
        List<String> x = new ArrayList<>();
        List<String> y = new ArrayList<>();
        if (day == null) {
            day = "30";
        }
        List< EffectiveProductionTimeByMineCodeDto> list =dwdCoalMineProduceDurationRtDMapper.getEffectiveProductionTimeByMineCodeAndDay(mineCode, day);
//        if (list.isEmpty()) {
//            vo.setX(x);
//            vo.setY(y);
//            return vo;
//        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        Date dateTime = null;
        for (int i = 0; i < Integer.parseInt(day); i++) {
            Boolean istrue = false;
            dateTime = Date.from(LocalDate.now().plusDays(-i).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
            for (EffectiveProductionTimeByMineCodeDto tt : list) {//日期相等
                if (dateTime.equals(tt.getStartTime())) {
                    istrue = true;
                    x.add(simpleDateFormat.format(dateTime));
                    y.add(String.valueOf(tt.getDuration()));
                    break;
                }
            }
            if (!istrue) {
                x.add(simpleDateFormat.format(dateTime));
                y.add("0");
            }

        }
        //倒序
        Collections.reverse(x);
        Collections.reverse(y);


        vo.setX(x);
        vo.setY(y);

        return vo;
    }

    /**
     * 获取所有煤矿有效生产时长统计
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public List<EffectiveProductionTimeByMineCodeVo> getEffectiveProductionTimeAllMineCode(Date startTime, Date endTime) {
        //获取所有井工矿
        List<SysOrganization> sysOrganizations = aqjkService.selectCodeUndergroundMiningSubMineList();
        if (sysOrganizations.isEmpty()) {
            return new ArrayList<>();
        }

        List<EffectiveProductionTimeByMineCodeVo> collect = sysOrganizations.stream().map(t -> {
            EffectiveProductionTimeByMineCodeVo vo = new EffectiveProductionTimeByMineCodeVo();
            vo.setMineCode(t.getOrgCode());
            vo.setMineName(t.getOrgName());
            List<EffectiveProductionTimeByMineCodeDto> effectiveProductionTimeByMineCode = this.getEffectiveProductionTimeByMineCode(t.getOrgCode(), startTime, endTime);
            vo.setDtos(effectiveProductionTimeByMineCode);
            return vo;
        }).collect(Collectors.toList());

        //过滤数据为空的煤矿
        collect.removeIf(t -> t.getDtos().isEmpty());

        return collect;
    }

    /**
     * 重点设备情况运行状态
     * @return
     */
    @Override
    public List<MineALlSwitchVo> equipmentSwitch(String companyCode, String mineCode) {
        //获取所有井工矿
        List<SysOrganization> sysOrganizations = aqjkService.selectCodeUndergroundMiningSubMineList(companyCode,mineCode);
        List<MineALlSwitchVo> voList = sysOrganizations.stream().map(t -> {
            MineALlSwitchVo vo = new MineALlSwitchVo();
            List<SwitchVo> miningSwitchVo = new ArrayList<>();
            List<SwitchVo> coalflowSwitchVo = new ArrayList<>();
            List<SwitchVo> fanSwitchVo = new ArrayList<>();
            List<SwitchVo> powerSwitchVo = new ArrayList<>();
            vo.setMineCode(t.getOrgCode());
            vo.setMineName(t.getOrgName());
            //获取当前煤矿的综采系统得开关信息
            DwdZdsbZcxtZcssTmpRtHPo zcSwitchVo = dwdZdsbZcxtZcssTmpRtHMapper.equipmentSwitch(t.getOrgCode());
            if (zcSwitchVo != null) {
                //有数据
                SwitchVo switchVo = new SwitchVo();
                switchVo.setDevName("采煤机");
                switchVo.setRunState(zcSwitchVo.getCdsz() == null ? "0" : zcSwitchVo.getCdsz());
                miningSwitchVo.add(switchVo);
            }
            //获取当前煤矿的主通风系统得开关信息
            List<DmZdsbZtfTfssYxztRtHPo> ztfSwitchVos = new ArrayList<>();
            //主通风灵泉煤矿特殊处理  此煤矿无数据上传时间可以卡创建时间最新
            if ("150781013603".equals(t.getOrgCode())) {
                //灵泉煤矿-主通风系统得开关信息
                DmZdsbZtfTfssYxztRtHPo ztfSwitchVos01 = dmZdsbZtfTfssYxztRtHMapper.equipmentSwitchByCreateTimeAndCode(t.getOrgCode(), "ZTF01");
                DmZdsbZtfTfssYxztRtHPo ztfSwitchVos02 = dmZdsbZtfTfssYxztRtHMapper.equipmentSwitchByCreateTimeAndCode(t.getOrgCode(), "ZTF02");
                if (ztfSwitchVos01 != null) {
                    ztfSwitchVos.add(ztfSwitchVos01);
                }
                if (ztfSwitchVos02 != null) {
                    ztfSwitchVos.add(ztfSwitchVos02);
                }
            } else {
                ztfSwitchVos = dmZdsbZtfTfssYxztRtHMapper.equipmentSwitch(t.getOrgCode());
            }
            //获取的数据按照Ztfbh进行分组 并且取最大值
            Map<String, DmZdsbZtfTfssYxztRtHPo> result = ztfSwitchVos.stream()
                    .filter(Objects::nonNull) // 过滤掉 null 元素
                    .filter(po -> po.getZtfbh() != null) // 过滤掉 ztfbh 为 null 的元素
                    .collect(Collectors.groupingBy(
                            DmZdsbZtfTfssYxztRtHPo::getZtfbh, // 按 Ztfbh 分组
                            Collectors.collectingAndThen(
                                    Collectors.maxBy(Comparator.comparing(DmZdsbZtfTfssYxztRtHPo::getCreateTime)), // 按 createTime 取最大值
                                    Optional::get // 提取 Optional 中的值
                            )
                    ));
            //获取主通风1
            DmZdsbZtfTfssYxztRtHPo ztfSwitchVo1 = result.get("ZTF01");
            if (ztfSwitchVo1 != null) {
                SwitchVo switchVo = new SwitchVo();
                switchVo.setDevName("1#");
                String value = ztfSwitchVo1.getCdsz() == null ? "0" : ztfSwitchVo1.getCdsz();
                if ("true".equals(value)) {
                    switchVo.setRunState("1");
                } else if ("false".equals(value)) {
                    switchVo.setRunState("0");
                } else {
                    switchVo.setRunState(value);
                }
                fanSwitchVo.add(switchVo);
            }
            //获取主通风2
            DmZdsbZtfTfssYxztRtHPo ztfSwitchVo2 = result.get("ZTF02");
            if (ztfSwitchVo2 != null ) {
                SwitchVo switchVo = new SwitchVo();
                switchVo.setDevName("2#");
                String value = ztfSwitchVo2.getCdsz() == null ? "0" : ztfSwitchVo2.getCdsz();
                if ("true".equals(value)) {
                    switchVo.setRunState("1");
                } else if ("false".equals(value)) {
                    switchVo.setRunState("0");
                } else {
                    switchVo.setRunState(value);
                }
                fanSwitchVo.add(switchVo);
            }
            //获取主运皮带
            DmZdsbZjtsztRtHPo zjtsztRtHPo = dmZdsbZjtsztRtHMapper.selectStatusOne(t.getOrgCode());
            if (zjtsztRtHPo != null) {
                SwitchVo switchVo = new SwitchVo();
                switchVo.setDevName("主井");
                switchVo.setRunState(zjtsztRtHPo.getCdsz() == null ? "0" : zjtsztRtHPo.getCdsz());
                coalflowSwitchVo.add(switchVo);
            }

            //获取供电
            PowerSwitchVo power = getPowerSwitchVo(t.getOrgCode());
            if (power != null) {
                //1回路
                SwitchVo switchVo1 = new SwitchVo();
                switchVo1.setDevName(power.getLin1());
                switchVo1.setRunState(String.valueOf(power.getStatus1()));
                powerSwitchVo.add(switchVo1);
                //2回路
                SwitchVo switchVo2 = new SwitchVo();
                switchVo2.setDevName(power.getLine2());
                switchVo2.setRunState(String.valueOf(power.getStatus2()));
                powerSwitchVo.add(switchVo2);
            }


            vo.setMiningSwitchVo(miningSwitchVo);
            vo.setCoalflowSwitchVo(coalflowSwitchVo);
            vo.setFanSwitchVo(fanSwitchVo);
            vo.setPowerSwitchVo(powerSwitchVo);
            return vo;
        }).collect(Collectors.toList());

        //过滤为空的数据  如果采煤和主通风 都是空的就过滤
        voList.removeIf(t -> t.getMiningSwitchVo().isEmpty() && t.getFanSwitchVo().isEmpty() && t.getCoalflowSwitchVo().isEmpty());
        return voList;
    }

    @Override
    public LeadInfoVO getTrailByName(String name, String mineCode) {
        LeadInfoVO vo = new LeadInfoVO();
        List<TrailVo> vos = new ArrayList<>();

        //查询这个人基本信息
        DwdRydwRyxxDPo rydwRyxxDPo =dwdRydwRyxxDMapper.selectRYxxOneByName(name, mineCode);
        //查询实时表  获取实时表内人员信息 根据煤矿编码和姓名
        RydwRyssPo rydwRyssPo = dwdRydwRyssHMapper.getTrailByName(name, mineCode);

        if (rydwRyssPo == null && rydwRyxxDPo == null) {
            vo.setTrailVos(vos);
            return vo;
        }
        if (rydwRyxxDPo != null) {
            vo.setCode(rydwRyxxDPo.getRykbm() == null ? "---" : rydwRyxxDPo.getRykbm());
            vo.setName(rydwRyxxDPo.getXm() == null ? name : rydwRyxxDPo.getXm());
            vo.setPosition(rydwRyxxDPo.getGz() == null ? "---" : rydwRyxxDPo.getZw());
            //部门
            vo.setDeptName(rydwRyxxDPo.getDzbzbm() == null ? "---" : rydwRyxxDPo.getDzbzbm());
        }else{
            vo.setName(name);
            vo.setCode("---");
            vo.setPosition("---");
            vo.setDeptName("---");
        }
        if (rydwRyssPo != null) {
            //工作状况
            vo.setWorkingCondition(rydwRyssPo.getRygzzt() == null ? "---" : rydwRyssPo.getRygzzt());
            //入井时间
            Date startTime = null;
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (StringUtils.isNotEmpty(rydwRyssPo.getRjsk())) {
                String rjsk = rydwRyssPo.getRjsk();
                try {
                    startTime = simpleDateFormat.parse(rjsk);
                    vo.setStartTime(startTime);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            }
            //出井时间
            if (StringUtils.isNotEmpty(rydwRyssPo.getCjsk())) {
                String cjsk = rydwRyssPo.getCjsk();
                try {
                    vo.setEndTime(simpleDateFormat.parse(cjsk));
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            }
            //持续时长 秒
            if (startTime != null) {
                long duration = (new Date().getTime() - startTime.getTime()) / 1000;
                vo.setDuration(duration);
            } else {
                vo.setDuration(0L);
            }

            //查询当前煤矿下所有基站
            List<RydwRyjzPo> rydwRyjzPos = dwdRydwRyjzDMapper.selectStationListByMineCode(mineCode);
            //转成map
            Map<String, RydwRyjzPo> rydwRyjzPoMap = rydwRyjzPos.stream()
                    .collect(Collectors.toMap(
                            RydwRyjzPo::getJzbm, // 键为 jzbm 属性
                            p -> Optional.ofNullable(p).orElse(new RydwRyjzPo()), // 值为 RydwRyjzPo 对象，处理可能为空的情况
                            (existing, replacement) -> existing)); // 解决重复键冲突的策略，保留已存在的值

            //获取的轨迹字段集合
            String xjgjjzsjjh = rydwRyssPo.getXjgjjzsjjh();
            //根据逗号拆分 每一个分站
            String[] split = xjgjjzsjjh.split(",");
            for (String s : split) {
                TrailVo trailVo = new TrailVo();
                //根据& 区分编码和时间
                String[] split1 = s.split("&");
                String stationCode = split1[0];
                String inStationCodeTime = split1[1];
                //获取分站详情
                RydwRyjzPo rydwRyjzPo = rydwRyjzPoMap.get(stationCode);
                trailVo.setSubstationCode(stationCode);
                trailVo.setInTime(inStationCodeTime);
                if (rydwRyjzPo != null) {
                    trailVo.setSubstationName(rydwRyjzPo.getJzmc() + "_" + rydwRyjzPo.getWzzs());
                    trailVo.setCoordinate_x(rydwRyjzPo.getXzb());
                    trailVo.setCoordinate_y(rydwRyjzPo.getYzb());
                    trailVo.setCoordinate_z(rydwRyjzPo.getZzb());
                } else {
                    trailVo.setSubstationName(stationCode);
                    trailVo.setCoordinate_x("0");
                    trailVo.setCoordinate_y("0");
                    trailVo.setCoordinate_z("0");
                }
                vos.add(trailVo);
            }
            // 倒序操作
//        Collections.reverse(vos);
        }



        vo.setTrailVos(vos);
        return vo;
    }

    @Override
    public LeadInfoVO getHisTrailByName(String name, String code,String inTime,String dataUpTime, String mineCode) {
        LeadInfoVO vo = new LeadInfoVO();
        List<TrailVo> vos = new ArrayList<>();

        //查询这个人基本信息
        DwdRydwRyxxDPo rydwRyxxDPo =dwdRydwRyxxDMapper.selectRYxxOneByName(name, mineCode);
        //查询实时表  获取实时表内人员信息 根据煤矿编码和姓名和入井时间查询轨迹
        DwdRydwRyssDPo rydwRyssPo = dwdRydwRyssDMapper.getHisTrailByName(name,code,inTime,dataUpTime,mineCode);

        if (rydwRyssPo == null && rydwRyxxDPo == null) {
            vo.setTrailVos(vos);
            return vo;
        }
        if (rydwRyxxDPo != null) {
            vo.setCode(rydwRyxxDPo.getRykbm() == null ? code : rydwRyxxDPo.getRykbm());
            vo.setName(rydwRyxxDPo.getXm() == null ? name : rydwRyxxDPo.getXm());
            vo.setPosition(rydwRyxxDPo.getGz() == null ? "---" : rydwRyxxDPo.getZw());
            //部门
            vo.setDeptName(rydwRyxxDPo.getDzbzbm() == null ? "---" : rydwRyxxDPo.getDzbzbm());
        }else{
            vo.setName(name);
            vo.setCode(code);
            vo.setPosition("---");
            vo.setDeptName("---");
        }
        if (rydwRyssPo != null) {
            //工作状况
            vo.setWorkingCondition(rydwRyssPo.getRygzzt() == null ? "---" : rydwRyssPo.getRygzzt());
            //入井时间
            Date startTime = null;
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (StringUtils.isNotEmpty(rydwRyssPo.getRjsk())) {
                String rjsk = rydwRyssPo.getRjsk();
                try {
                    startTime = simpleDateFormat.parse(rjsk);
                    vo.setStartTime(startTime);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            }
            //出井时间
            if (StringUtils.isNotEmpty(rydwRyssPo.getCjsk())) {
                String cjsk = rydwRyssPo.getCjsk();
                try {
                    vo.setEndTime(simpleDateFormat.parse(cjsk));
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            }
            //持续时长 秒
            if (startTime != null) {
                long duration = (new Date().getTime() - startTime.getTime()) / 1000;
                vo.setDuration(duration);
            } else {
                vo.setDuration(0L);
            }

            //查询当前煤矿下所有基站
            List<RydwRyjzPo> rydwRyjzPos = dwdRydwRyjzDMapper.selectStationListByMineCode(mineCode);
            //转成map
            Map<String, RydwRyjzPo> rydwRyjzPoMap = rydwRyjzPos.stream()
                    .collect(Collectors.toMap(
                            RydwRyjzPo::getJzbm, // 键为 jzbm 属性
                            p -> Optional.ofNullable(p).orElse(new RydwRyjzPo()), // 值为 RydwRyjzPo 对象，处理可能为空的情况
                            (existing, replacement) -> existing)); // 解决重复键冲突的策略，保留已存在的值

            //获取的轨迹字段集合
            String xjgjjzsjjh = rydwRyssPo.getXjgjjzsjjh();
            //根据逗号拆分 每一个分站
            String[] split = xjgjjzsjjh.split(",");
            for (String s : split) {
                TrailVo trailVo = new TrailVo();
                //根据& 区分编码和时间
                String[] split1 = s.split("&");
                String stationCode = split1[0];
                String inStationCodeTime = split1[1];
                //获取分站详情
                RydwRyjzPo rydwRyjzPo = rydwRyjzPoMap.get(stationCode);
                trailVo.setSubstationCode(stationCode);
                trailVo.setInTime(inStationCodeTime);
                if (rydwRyjzPo != null) {
                    trailVo.setSubstationName(rydwRyjzPo.getJzmc() + "_" + rydwRyjzPo.getWzzs());
                    trailVo.setCoordinate_x(rydwRyjzPo.getXzb());
                    trailVo.setCoordinate_y(rydwRyjzPo.getYzb());
                    trailVo.setCoordinate_z(rydwRyjzPo.getZzb());
                } else {
                    trailVo.setSubstationName(stationCode);
                    trailVo.setCoordinate_x("0");
                    trailVo.setCoordinate_y("0");
                    trailVo.setCoordinate_z("0");
                }
                vos.add(trailVo);
            }
            // 倒序操作
//        Collections.reverse(vos);
        }



        vo.setTrailVos(vos);
        return vo;
    }

    /**
     * pc-主页-矿井类型
     * @param companyCode
     * @param mineCode
     * @return
     */
    @Override
    public List<MineTypeVo> mineType(String companyCode, String mineCode) {
        List<CoalMineBasicDisasterIntelligentInfoPo> coalMineBasicDisasterIntelligentInfoPos = coalMineBasicDisasterIntelligentInfoMapper.selectList(
                new LambdaQueryWrapper<CoalMineBasicDisasterIntelligentInfoPo>()
                        .eq(StringUtils.isNotBlank(companyCode), CoalMineBasicDisasterIntelligentInfoPo::getMqCode, companyCode)
                        .eq(StringUtils.isNotBlank(mineCode), CoalMineBasicDisasterIntelligentInfoPo::getMkCode, mineCode));

        List<MineTypeVo> vos = new ArrayList<>();

        //高瓦斯
        List<CoalMineBasicDisasterIntelligentInfoPo> highGasList = coalMineBasicDisasterIntelligentInfoPos.stream()
                .filter(t -> "1".equals(t.getHighGasFlag()))
                .collect(Collectors.toList());
        MineTypeVo highGasVo = new MineTypeVo();
        highGasVo.setIcon("high_gas");
        highGasVo.setName("高瓦斯");
        highGasVo.setNumber(highGasList.size());
        highGasVo.setDtoList(highGasList);
        vos.add(highGasVo);

        //煤与瓦斯突出
        List<CoalMineBasicDisasterIntelligentInfoPo> coalAndGasList = coalMineBasicDisasterIntelligentInfoPos.stream()
                .filter(t -> "1".equals(t.getCoalGasOutburstFlag()))
                .collect(Collectors.toList());
        MineTypeVo coalAndGasVo = new MineTypeVo();
        coalAndGasVo.setIcon("coal_gas");
        coalAndGasVo.setName("煤与瓦斯突出");
        coalAndGasVo.setNumber(coalAndGasList.size());
        coalAndGasVo.setDtoList(coalAndGasList);
        vos.add(coalAndGasVo);

        //冲击地压
        List<CoalMineBasicDisasterIntelligentInfoPo> impactGeologyList = coalMineBasicDisasterIntelligentInfoPos.stream()
                .filter(t -> "1".equals(t.getRockBurstTypeFlag()))
                .collect(Collectors.toList());
        MineTypeVo impactGeologyVo = new MineTypeVo();
        impactGeologyVo.setIcon("rock_burst");
        impactGeologyVo.setName("冲击地压");
        impactGeologyVo.setNumber(impactGeologyList.size());
        impactGeologyVo.setDtoList(impactGeologyList);
        vos.add(impactGeologyVo);


        //水文地质复杂
        List<CoalMineBasicDisasterIntelligentInfoPo> seawaterList = coalMineBasicDisasterIntelligentInfoPos.stream()
                .filter(t -> "1".equals(t.getHydrogeologicalComplexFlag()))
                .collect(Collectors.toList());
        MineTypeVo seawaterVo = new MineTypeVo();
        seawaterVo.setIcon("hydrology");
        seawaterVo.setName("水文地质复杂");
        seawaterVo.setNumber(seawaterList.size());
        seawaterVo.setDtoList(seawaterList);
        vos.add(seawaterVo);

        //国家智能化矿井
        List<CoalMineBasicDisasterIntelligentInfoPo> nationalList = coalMineBasicDisasterIntelligentInfoPos.stream()
                .filter(t -> "1".equals(t.getNationalIntelligentFlag()))
                .collect(Collectors.toList());
        MineTypeVo nationalVo = new MineTypeVo();
        nationalVo.setIcon("mine");
        nationalVo.setName("国家智能化矿井");
        nationalVo.setNumber(nationalList.size());
        nationalVo.setDtoList(nationalList);
        vos.add(nationalVo);


        //省级智能化矿井
        List<CoalMineBasicDisasterIntelligentInfoPo> provinceList = coalMineBasicDisasterIntelligentInfoPos.stream()
                .filter(t -> "1".equals(t.getProvincialIntelligentFlag()))
                .collect(Collectors.toList());
        MineTypeVo provinceVo = new MineTypeVo();
        provinceVo.setIcon("mine");
        provinceVo.setName("省级智能化矿井");
        provinceVo.setNumber(provinceList.size());
        provinceVo.setDtoList(provinceList);
        vos.add(provinceVo);

        //智能化回采面
        List<CoalMineBasicDisasterIntelligentInfoPo> backhoeList = coalMineBasicDisasterIntelligentInfoPos.stream()
                .filter(t -> t.getIntelligentMiningWorkingfaceQty() !=null && t.getIntelligentMiningWorkingfaceQty() != "0")
                .collect(Collectors.toList());
        int backhoeSum = backhoeList.stream()
                .mapToInt(t -> Integer.parseInt(t.getIntelligentMiningWorkingfaceQty()))
                .sum();

        MineTypeVo backhoeVo = new MineTypeVo();
        backhoeVo.setIcon("surface");
        backhoeVo.setName("智能化回采面");
        backhoeVo.setNumber(backhoeSum);
        backhoeVo.setDtoList(backhoeList);
        vos.add(backhoeVo);

        //智能化掘进面
        List<CoalMineBasicDisasterIntelligentInfoPo> mineList = coalMineBasicDisasterIntelligentInfoPos.stream()
                .filter(t -> t.getIntelligentTunnelWorkingfaceQty() !=null && t.getIntelligentTunnelWorkingfaceQty() != "0")
                .collect(Collectors.toList());

        int mineSum = mineList.stream().mapToInt(t -> Integer.parseInt(t.getIntelligentTunnelWorkingfaceQty())).sum();
        MineTypeVo mineVo = new MineTypeVo();
        mineVo.setIcon("surface");
        mineVo.setName("智能化掘进面");
        mineVo.setNumber(mineSum);
        mineVo.setDtoList(mineList);
        vos.add(mineVo);
        return vos;
    }

    /**
     * pc-主页-安全天数
     * @param companyCode
     * @param mineCode
     * @return
     */
    @SneakyThrows
    @Override
    public String safeDays(String companyCode, String mineCode) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date safeDays = new Date();
        if (StringUtils.isEmpty(mineCode) && StringUtils.isEmpty(companyCode)) {
            //煤业安全生产天数  从
            //2022-11-28
            safeDays = sdf.parse("2022-11-28");
        }else if ("91150781720169744B".equals(companyCode)) {
            safeDays=sdf.parse("2024-06-24");
        }
        long safetyDays = (new Date().getTime() - safeDays.getTime()) / 24 / 60 / 60 / 1000;
        return String.valueOf(safetyDays);
    }

    public PowerSwitchVo getPowerSwitchVo(String mineCode) {
        List<PowerSwitchVo> mineInfoList = new ArrayList<>();

        // 使用带参数的构造器创建 MineInfo 对象并添加到列表中
        mineInfoList.add(new PowerSwitchVo("华亭煤矿", "620824009663",1, 0, "3513华砚一线", "3524华砚二线"));
        mineInfoList.add(new PowerSwitchVo("砚北煤矿", "620824009734",0, 1, "3522石南线", "3514砚南线"));
        mineInfoList.add(new PowerSwitchVo("陈家沟煤矿","620824009382", 0, 1, "612华管一线", "621华管二线"));
        mineInfoList.add(new PowerSwitchVo("东峡煤矿", "620824009235",0, 1, "6107东峡一线", "207东峡二线"));
        mineInfoList.add(new PowerSwitchVo("山寨煤矿", "620824009091",1, 0, "3523石山线", "3521策山线"));
        mineInfoList.add(new PowerSwitchVo("新窑煤矿", "620823009692",1, 0, "611新窑一线", "621新窑二线"));
        mineInfoList.add(new PowerSwitchVo("新柏煤矿", "620823009365",0, 1, "新柏3514线", "新柏3524线"));
        mineInfoList.add(new PowerSwitchVo("大柳煤矿", "620823009724",1, 0, "3512石大线", "3523新大线"));
        mineInfoList.add(new PowerSwitchVo("赤城煤矿", "620823009721",0, 1, "新矿3515线", "新矿3522线"));
        mineInfoList.add(new PowerSwitchVo("灵泉煤矿", "150781013603",0, 1, "323风井变", "311总控变"));
        mineInfoList.add(new PowerSwitchVo("铁北煤矿", "150781013194",1, 0, "312二采变", "321总控变"));
        mineInfoList.add(new PowerSwitchVo("灵东煤矿", "150781013670",1, 0, "151灵东1线", "153灵东2线"));
        mineInfoList.add(new PowerSwitchVo("灵露煤矿", "150781013671",0, 1, "311东站一回", "321东站二回"));
        mineInfoList.add(new PowerSwitchVo("西川煤矿", "610204017042",1, 0, "3590柳西一线", "3597柳西二线"));
        mineInfoList.add(new PowerSwitchVo("青岗坪煤矿","610429017222", 1, 0, "3611青寺线", "3581青弟线"));
        mineInfoList.add(new PowerSwitchVo("柳巷煤矿", "610802003155",1, 0, "3576柳盘线", "3602柳北线"));
        mineInfoList.add(new PowerSwitchVo("核桃峪煤矿", "621025009717",1, 0, "裕供线", "裕乐线"));
        mineInfoList.add(new PowerSwitchVo("新庄煤矿", "621026009696",1, 0, "新乐1回线", "新乐2回线"));
        mineInfoList.add(new PowerSwitchVo("白龙山煤矿一井", "530325010583",1, 0, "滇白线", "滇老线"));
        mineInfoList.add(new PowerSwitchVo("雨汪煤矿一井", "530325010577",0, 1, "老雨线", "老厂线"));
        mineInfoList.add(new PowerSwitchVo("高头窑煤矿", "150621011015",1, 0, "丘家塔一回线", "丘家塔二回线"));

        return mineInfoList.stream().filter(t -> t.getMineCode().equals(mineCode)).findFirst().orElse(null);
    }

    public List<JyglDwmcEntityPo> getFineListByCode(String mineCode) {
        List<JyglDwmcEntityPo> dwmcEntities = jyglDwmcEntityMapper.selectList(new LambdaQueryWrapper<JyglDwmcEntityPo>().eq(StringUtils.isNotBlank(mineCode), JyglDwmcEntityPo::getOrgId, mineCode));
        if (dwmcEntities.isEmpty()) {
            return new ArrayList<>();
        }
        return dwmcEntities;
    }


    public List<JyglShiftManagementPo> getFineDataBeOnWatchListBymineName(String mineName) {

        //获取当天带值班记录列表
        List<JyglShiftManagementPo> list = jyglShiftManagementMapper.getFineDataBeOnWatchListBymineName(mineName);
        if (list.isEmpty()) {
            return new ArrayList<>();
        }

        return list;
    }


    public List<JyglInsertShiftManage1Po> getFineDataClassListBymineName(String mineName) {
        List<JyglInsertShiftManage1Po> insertShiftManage1Pos = jyglInsertShiftManage1Mapper.selectList(new LambdaQueryWrapper<JyglInsertShiftManage1Po>()
                .eq(StringUtils.isNotBlank(mineName), JyglInsertShiftManage1Po::getDw, mineName));
        if (insertShiftManage1Pos.isEmpty()) {
            return new ArrayList<>();
        }
        return insertShiftManage1Pos;
    }

    private String getDuration(Date startTime, Date endTime) {
        LocalDateTime startDateTime = LocalDateTime.ofInstant(startTime.toInstant(), java.time.ZoneId.systemDefault());
        LocalDateTime endDateTime = LocalDateTime.ofInstant(endTime.toInstant(), java.time.ZoneId.systemDefault());
        Duration duration = Duration.between(startDateTime, endDateTime);

        long totalSeconds = duration.getSeconds();
        long days = totalSeconds / (24 * 3600);
        long hours = (totalSeconds % (24 * 3600)) / 3600;
        long minutes = (totalSeconds % 3600) / 60;
        long seconds = totalSeconds % 60;

        StringBuilder timeString = new StringBuilder();
        if (days > 0) {
            timeString.append(days).append("天");
        }
        if (hours > 0 || days > 0) { // Include hours if there's at least one day or any hours
            timeString.append(hours).append("小时");
        }
        if (minutes > 0 || hours > 0 || days > 0) { // Include minutes if there's at least one hour or any minutes
            timeString.append(minutes).append("分钟");
        }
        timeString.append(seconds).append("秒");

        return timeString.toString();
    }

    // 判断当前时间属于哪个班次的方法
    private String determineShift(String nowTime, Map<String, List<String>> clases) {
        String shift = "";
        for (Map.Entry<String, List<String>> entry : clases.entrySet()) {
            String key = entry.getKey();
            List<String> value = entry.getValue();
            if (value.isEmpty() || value.size() != 2) {
                //不用判断  没有时间段  直接跳过比较
                continue;
            }
            boolean between = this.isBetween(nowTime, value);
            if (between) {
                shift = key;
            }
        }
        return shift;
    }

    // 辅助方法，判断时间是否在指定范围内
    private boolean isBetween(String nowTime,List<String> times) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
            String startTime = times.get(0);
            String endTime = times.get(1);
            Date now = sdf.parse(nowTime);
            Date start = sdf.parse(startTime);
            Date end = sdf.parse(endTime);

            // 如果结束时间跨越了午夜边界  0：00
            if (end.before(start)) {
                Calendar endCal = Calendar.getInstance();
                endCal.setTime(end);
                endCal.add(Calendar.DAY_OF_MONTH, 1); // 添加一天
                end = endCal.getTime();
            }

            // 判断当前时间是否在开始时间和结束时间之间
            return now.compareTo(start) >= 0 && now.compareTo(end) < 0;
        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }
    }
}
